<template>
  <div>
    <!-- 双方基础信息 -->
    <div class="card-wrap flex-column justify-end card-padding">
      <div class="card-title-wrap">
        <span>合同基础信息</span>
        <span></span>
      </div>
      <el-form :model="form" ref="bothParties" :disabled="type == 'detail'" label-width="170px" :rules="rules" :label-position="type == 'detail' ? 'right' : 'top'">
        <div :style="{ marginLeft: type == 'detail' ? '' : '50px' }" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; position: relative">
          <el-form-item label="业务担当姓名:" prop="businessPersonId" :style="{ minWidth: type == 'detail' ? '48%' : '33%' }">
            <el-select filterable maxlength="30" v-model="form.businessPersonId" clearable style="width: 80%">
              <el-option v-for="dict in businessList" :label="dict.userName" :value="dict.userId" :key="dict.userId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出租方:" prop="lessorId" :style="{ minWidth: type == 'detail' ? '48%' : '33%' }">
            <el-select filterable maxlength="30" v-model="form.lessorId" clearable style="width: 80%">
              <el-option v-for="dict in rentOutList" :label="dict.deptName" :value="dict.deptId" :key="dict.deptId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="承租方:" prop="leaseeId" :style="{ minWidth: type == 'detail' ? '48%' : '33%' }">
            <el-select filterable maxlength="30" v-model="form.leaseeId" filterable style="width: 80%" @change="changeCzf">
              <el-option v-for="dict in CustomerList" :key="dict.customerId" :label="dict.customerName" :value="dict.customerId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型:" prop="invoiceType" :style="{ minWidth: type == 'detail' ? '48%' : '33%' }">
            <el-select filterable maxlength="30" v-model="form.invoiceType" clearable style="width: 80%">
              <el-option v-for="dict in dict.type.order_invoice_type" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-tooltip class="item" effect="dark" content="出租方给承租方开具的发票类型" placement="right">
            <el-button circle style="border: none; background-color: #fff; font-size: 12px; position: absolute; font-weight: bold" :style="{
                left: type == 'detail' ? '50px' : '-30px',
                top: type == 'detail' ? '50px' : '90px',
              }">？</el-button>
          </el-tooltip>
          <el-form-item label="客户紧急联系人姓名:" prop="contactPersonId" :style="{ minWidth: type == 'detail' ? '48%' : '33%' }">
            <el-select filterable maxlength="30" v-model="form.contactPersonId" clearable style="width: 80%">
              <el-option v-for="dict in customerListIphone" :label="dict.contactName" :value="dict.contactId" :key="dict.contactId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户紧急联系人电话:" :style="{ minWidth: type == 'detail' ? '48%' : '33%' }">
            <el-input v-model="contactMobile" readonly style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="租赁用途:" :style="{ minWidth: type == 'detail' ? '48%' : '33%' }">
            <el-select v-model="form.purposeType" clearable filterable style="width: 80%">
              <el-option v-for="dict in dict.type.order_purpose_type" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-row style="margin-left: 50px; margin-top: 20px">
          <el-col :span="12">
            <div>
              <span style="font-size: 14px; color: #606266">额度申请编号:</span>
              <span @click="goToEdDetail($route.query.calcSchemeId)" style="margin-left: 10px; color: #1890ff; cursor: pointer">{{ $route.query.calcSchemeCode ? $route.query.calcSchemeCode : form.calcSchemeCode }}</span>
            </div>
          </el-col>
          <el-col :span="12" v-if="form.orderId">
            <div>
              <span style="font-size: 14px; color: #606266">订单编号:</span>
              <span style="margin-left: 10px; color: #1890ff; cursor: pointer" @click="orderDetail(form)">{{ form.orderCode }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-left: 50px; margin-top: 20px">
          <el-col :span="12">
            <div>
              <span style="font-size: 14px; color: #606266">信审编号:</span>
              <span @click="goToXsDetail($route.query.applicationNo)" style="margin-left: 10px; color: #1890ff; cursor: pointer">{{ $route.query.applicationNo ? $route.query.applicationNo : form.applicationNo }}</span>
            </div>
          </el-col>
        </el-row>
        <el-table :data="form.supplementDriverList" style="width: 95%; margin: 0 auto; margin-top: 30px">
          <el-table-column label="司机姓名" align="center">
            <template slot-scope="scope">
              <el-select filterable v-model="scope.row.driverId" style="width: 70%" @change="changeDriver(scope)">
                <el-option v-for="dict in driverListData" :label="dict.driverName" :value="dict.driverId" :key="dict.driverId"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="司机手机号" align="center">
            <template slot-scope="scope">
              <el-input style="width: 70%" v-model="scope.row.driverMobile" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column label="司机身份证号" align="center">
            <template slot-scope="scope">
              <el-input style="width: 70%" v-model="scope.row.driverIdNo" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column width="70" v-if="type !== 'detail'">
            <template slot-scope="scope">
              <i class="el-icon-delete" style="cursor: pointer" @click="dele(scope)"></i>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center" v-if="type !== 'detail'">
          <el-button type="text" size="mini" icon="el-icon-plus" @click="addDriver">添加司机</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getCorrelationCompany, customerList, userList, getDriverList, getCustomerContacts } from '@/api/vehicleOrder'
export default {
  name: 'bothParties',
  dicts: ['order_invoice_type', 'order_purpose_type'],
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: '',
    },
  },
  computed: {
    form: {
      get() {
        let that = this
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key)
          },
          set(target, key, value) {
            that.$emit('input', { ...target, [key]: value })
            return true
          },
        })
        return proxy
      },
    },
    contactMobile() {
      return this.form.contactPersonId ? this.customerListIphone.filter((item) => item.contactId == this.form.contactPersonId)[0]?.contactPhone : ''
    },
    type() {
      let status
      switch (this.state) {
        case 'write':
          status = 'edit'
          break
        case 'disabled':
          status = 'detail'
          break
        case 'readonly':
          status = 'detail'
          break
        case 'detail':
          status = 'detail'
          break
        case 'edit':
          status = 'edit'
        case 'add':
          status = 'add'
          break
      }
      return status
    },
  },
  watch: {
    'value.lessorId': {
      handler(val) {
        if (val) {
          this.getCorrelationCompany()
        }
      },
      immediate: true,
      deep: true,
    },
    'value.leaseeId': {
      handler(val) {
        if (val) {
          this.customerList()
          this.getCustomerContacts()
        }
      },
      immediate: true,
      deep: true,
    },
    'value.lessorIdCopy': {
      handler(val) {
        if (val) {
          this.getCorrelationCompany()
        }
      },
      immediate: true,
      deep: true,
    },
    'value.leaseeIdCopy': {
      handler(val) {
        if (val) {
          this.customerList()
          this.getCustomerContacts()
        }
      },
      immediate: true,
      deep: true,
    },
    '$route.query.lessorId': {
      handler(val) {
        if (val) {
          this.getCorrelationCompany()
        }
      },
      immediate: true,
      deep: true,
    },
    '$route.query.leaseeId': {
      handler(val) {
        if (val) {
          this.customerList()
          this.getCustomerContacts()
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      driverListData: [],
      businessList: [],
      rentOutList: [],
      CustomerList: [],
      customerListIphone: [],
      rules: {
        businessPersonId: [
          {
            required: true,
            message: '请选择业务担当姓名:',
            trigger: 'change',
          },
        ],
        lessorId: [
          {
            required: true,
            message: '请选择出租方',
            trigger: 'change',
          },
        ],
        leaseeId: [
          {
            required: true,
            message: '请选择承租方',
            trigger: 'change',
          },
        ],
        invoiceType: [
          {
            required: true,
            message: '请选择发票类型',
            trigger: 'change',
          },
        ],
        contactPersonId: [
          {
            required: true,
            message: '请选择客户紧急联系人姓名',
            trigger: 'change',
          },
        ],
      },
    }
  },
  created() {
    this.userList()
    this.getDriverList()
  },
  methods: {
    goToXsDetail(applicationNo, id) {
      this.$router.push({
        name: 'LetterReviewDetail',
        query: {
          applicationNo: applicationNo ? applicationNo : this.form.applicationNo,
          id,
        },
      })
    },
    goToEdDetail(calcSchemeId) {
      this._toPage({
        path: '/quota/ApplyDetails',
        query: {
          calcSchemeId: calcSchemeId ? calcSchemeId : this.form.calcSchemeId,
        },
      })
    },
    // 订单详情
    orderDetail(row) {
      this._toPage({
        name: 'OrderDetails',
        query: {
          type: row.carType,
          orderId: row.orderId,
          calcSchemeId: row.calcSchemeId,
        },
      })
    },
    changeCzf() {
      console.log(this.form.leaseeId, 'this.form.leaseeId ')
      this.getCustomerContacts()
    },

    // 下拉选择司机
    changeDriver(scope) {
      console.log(scope.row, scope.$index, this.driverListData, '0-0-0-0-0-0-0-0-0-0')
      let driverPhone = this.driverListData
        .map((v) => {
          if (v.driverId == scope.row.driverId) {
            return v.driverPhone
          }
        })
        .filter((i) => i)[0]
      let driverName = this.driverListData
        .map((v) => {
          if (v.driverId == scope.row.driverId) {
            return v.driverName
          }
        })
        .filter((i) => i)[0]
      let driverLicenseNo = this.driverListData
        .map((v) => {
          if (v.driverId == scope.row.driverId) {
            return v.driverLicenseNo
          }
        })
        .filter((i) => i)[0]
      console.log(driverName, 'driverLicenseNo')
      this.form.supplementDriverList[scope.$index].driverMobile = driverPhone
      this.form.supplementDriverList[scope.$index].driverIdNo = driverLicenseNo
      this.form.supplementDriverList[scope.$index].driverName = driverName
    },
    // 添加司机
    addDriver() {
      this.form.supplementDriverList.push({})
    },
    // 删除
    dele(scope) {
      this.form.supplementDriverList.splice(scope.$index, 1)
    },
    // 司机下拉
    async getDriverList() {
      try {
        let res = await getDriverList()
        this.driverListData = res.data.map((v) => {
          return {
            ...v,
            driverName: `${v.driverName}(${v.driverPhone})`,
          }
        })
      } catch (error) { }
    },
    async customerList() {
      let params = {
        customerId: this.$route.query.leaseeId || this.form.leaseeId || this.form.leaseeIdCopy,
      }
      try {
        let res = await customerList(params)
        this.CustomerList = res.data
      } catch (error) { }
    },
    async getCustomerContacts() {
      try {
        let res = await getCustomerContacts(this.$route.query.leaseeId || this.form.leaseeId || this.form.leaseeIdCopy)
        this.customerListIphone = res.data
      } catch (error) { }
    },
    async userList() {
      try {
        let res = await userList()
        this.businessList = res.rows
      } catch (error) { }
    },
    async getCorrelationCompany() {
      let params = {
        deptId: this.$route.query.lessorId || this.form.lessorId || this.form.lessorIdCopy,
        deptType: 2,
      }
      try {
        let res = await getCorrelationCompany(params)
        this.rentOutList = res.data
        console.log(res, 'res出租方')
      } catch (error) { }
    },
    valid() {
      return new Promise(async (resolve) => {
        let result = true
        let refs = Object.values(this.$refs)
        for (let index = 0; index < refs?.length; index++) {
          const ref = refs[index]
          if (Object.prototype.toString.call(ref) == '[object Array]') {
            for (let i = 0; i < ref.length; i++) {
              const element = ref[i]
              if (element?.valid) {
                let rc = await element?.valid?.()
                result = result && rc
              }
              if (element?.validate) {
                let rf = await this._valid(ref)
                result = result && rf
              }
              if (element?.form_validate) {
                let rf = await this._valid(ref, 'form_validate')
                result = result && rf
              }
            }
          } else {
            if (ref?.valid) {
              let rc = await ref?.valid?.()
              result = result && rc
            }
            if (ref?.validate) {
              let rf = await this._valid(ref)
              result = result && rf
            }
            if (ref?.form_validate) {
              let rf = await this._valid(ref, 'form_validate')
              result = result && rf
            }
          }
        }
        resolve(result)
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.box {
  width: 100%;

  .title {
    border-left: 3px solid #3280fc;
    padding-left: 5px;
    box-sizing: border-box;
  }
}
.app-container {
  background-color: #fff;
}
</style>
